<?php
function contact_onLoad($db) {
	// Setup a one time token to protect against spam relays
	global $token;
	$token = new Zend_Session_Namespace('emailToken');
	$token->setExpirationSeconds(3600);
	if (!isset($token->id))
		$token->id = mt_rand();
}

function contact_main($db, &$view, $translate) {
	require_once 'Zend/Validate/EmailAddress.php';
	require_once 'libs/recaptcha/recaptchalib.php';
	global $config;
	if (empty($config['sitecontact']))
		throw new Exception("This module is disabled due to missing contact info.");
	$data = $db->fetchRow("SELECT * FROM `recaptcha`");
	$validator = new Zend_Validate_EmailAddress();
	$validCaptcha = true;
	if (!isset($GLOBALS['token']->id))
		 die("Bad token.  Please check that cookies are enabled for this site.\n");
	if (isset($_POST['contact_submit']) && !empty($data['privatekey'])) {
		$resp = recaptcha_check_answer($data['privatekey'],
									$_SERVER["REMOTE_ADDR"],
									$_REQUEST["recaptcha_challenge_field"],
									$_REQUEST["recaptcha_response_field"]);
		if (!$resp->is_valid) {
			$validCaptcha = false;
			$view->assign("captchaError", recaptcha_get_html($data['publickey'], $resp->error));
		}
	}
	if (isset($_POST['contact_submit']) && $validator->isValid($_REQUEST['email']) && $validCaptcha) {
		mail($config['sitecontact'], $_REQUEST['subject'], $_REQUEST['message'], "From: " . $_REQUEST['email'] . "\r\n") or die("Mail configuration error.\n");
		$GLOBALS['logger']->log('Mail sent from ' . $_REQUEST['email'] . ' with IP ' . $_SERVER['REMOTE_ADDR'], Zend_Log::NOTICE);
		echo "Message Sent!  Thank you.\n";
	} else {
		$view->assign("valid", $validator);
		if (!empty($data['publickey']))
			$view->assign("captcha", recaptcha_get_html($data['publickey']));
		$view->display('contact.tpl');
	}
}
?>
